#include "stm32_fork.h"
#include "cJSON.h"

int main(int argc,char *argv[]){
    int servfd = -1;
	int intport = -1;
    unsigned short port = 0;

    intport = PORT_STM32;
    if(intport < 0 || intport > 0xFFFF){
        printf("The port:%d is invalid\n",intport);
        return 2;
    }
    port = intport;

	servfd = create_tcp_server_socket(IP_STM32,port,9);
    server_main_loop(servfd);

	close(servfd);
	servfd = -1;
	return 0;
}

int create_tcp_server_socket(const char *psvrip,unsigned short svrport,int backlog){
        int servfd = -1;
        struct sockaddr_in servaddr;
        int ret = 0;

        servfd = socket(AF_INET,SOCK_STREAM,0);
         printf("TCP模式\n");
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(svrport);
        inet_aton(psvrip,&servaddr.sin_addr);
        ret = bind(servfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
        printf("端口号: %d  ,添加地址为 : %s \n",svrport,psvrip);
        ret += listen(servfd,backlog);
        printf("监听完成\n");
        if(ret){
            printf("bind or listen failed\n");
            close(servfd);
            servfd = -1;
            return -1;
        }
        return servfd;
}

int server_main_loop(int fd){
	int datafd = -1;
    pthread_t tid_1;
    pthread_t tid_2;
    int ret = 0;
	while(1){     
        printf("等待客户端的连接\n");
		datafd = accept(fd,NULL,NULL);
        printf("客户端的连接完成\n");
                
		if(datafd < 0){
			if(errno == EINTR)	continue;
			else{
				printf("Accept error\n");
				break;
			}
		}
        ret = pthread_create(&tid_1, NULL, handle_client, (void *)(long)datafd);
        if (ret != 0){
            close(datafd);
            datafd = -1;
            printf("pthread_create failed for handle_client\n");
            continue;
        }

        ret = pthread_create(&tid_2, NULL, masget_init, (void *)(long)datafd);
        if (ret != 0) {
            close(datafd);
            datafd = -1;
            printf("pthread_create failed for masget_init\n");
            continue;
        }
	}
	return 0;
}

void *handle_client(void *parg){
    int datafd = (int)(long)parg;
    pthread_detach(pthread_self());
    char arr[1024];
    ssize_t bytes_read;

    printf("创建共享内存.....\n");
    int shmid = shmget(msg_key_get, sizeof(arr), IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1) {
        // 检查错误是因为已经存在还是其他原因
        if (errno == EEXIST)    shmid = shmget(msg_key_get, sizeof(arr), 0);
        else {
            perror("shmget");
            close(datafd);
            return NULL;
        }
    }

    char *p = shmat(shmid, NULL, 0);
    if (p == (void *)-1){
        perror("shmat");
        close(datafd);
        return NULL;
    }
    printf("共享内存创建完成\n");
    printf("读取STM32数据....\n");
    while ((bytes_read = read(datafd, arr, sizeof(arr) - 1)) > 0){
        arr[bytes_read] = '\0';

        if (strcmp(arr, "STM32_ID_01") == 0)    write(datafd, arr, bytes_read + 1); 
        else{
            printf("写入的数据：%s\n", arr);
            memcpy(p, arr, bytes_read + 1);
        }
        memset(arr, 0, sizeof(arr));
    }
    if (bytes_read < 0)    perror("read");
    else    printf("Client closed connection\n");
    close(datafd);
    shmdt(p); // 删除共享内存段

    return NULL;
}

// 消息队列
void *masget_init(void *parg){ 
    int datafd = (int)(long)parg;
    struct msgbuf mb;
    int msgid, ret;
    pthread_detach(pthread_self());
	msgid = msgget(msg_key, IPC_CREAT|0777);
	if(msgid < 0){
		perror("msget");
		return  NULL;
	}
	printf("信息队列创建成功,msg_id:%d\n",msgid);

    while(1){
        ret = msgrcv(msgid, &mb,512, MSG_TYPE, 0);
        if(ret < 0){
            perror("msgrcv");
            return NULL;
        }
        mb.mtext[ret] = '\0'; // 确保字符串以空字符结束
        write(datafd, mb.mtext, ret); // 写入实际接收到的数据长度
        printf("收到消息队列中JSON数据: %s\n", mb.mtext);
    }
}
